package com.eee.machine.service.impl;

import com.eee.machine.beans.TChannelProduct;
import com.eee.machine.beans.TMachine;
import com.eee.machine.beans.TMemberMachine;
import com.eee.machine.common.OperateResponse;
import com.eee.machine.common.OrderItem;
import com.eee.machine.common.TableData;
import com.eee.machine.concurrent.OrderHashMap;
import com.eee.machine.dao.mapper.TChannelProductMapper;
import com.eee.machine.dao.mapper.TMachineMapper;
import com.eee.machine.dao.mapper.TMemberMachineMapper;
import com.eee.machine.service.IMachineService;
import com.eee.machine.utils.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;


@Service
public class IMachineServiceImpl implements IMachineService {

    @Autowired
    private TChannelProductMapper channelProductMapper;
    @Autowired
    private TMachineMapper machineMapper;
    @Autowired
    private TMemberMachineMapper tMemberMachineMapper;

    @Override
    public TableData getAllMachine(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List<TMachine> tMachines = machineMapper.selectByExample(null);
        PageInfo<TMachine> pageInfo = new PageInfo<>(tMachines);
        return new TableData((int)pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    @Transactional
    public OperateResponse bindingMember(String Phone, String machineId) {
        TMemberMachine tMemberMachine = new TMemberMachine();
        tMemberMachine.settMemberMachineId(UUIDUtil.generate());
        tMemberMachine.settMemberPhone(Phone);
        tMemberMachine.settMachineId(machineId);
        tMemberMachine.setDeleteFlag((short)0);
        tMemberMachine.setCreateDatetime(new Date());
        int insert = tMemberMachineMapper.insert(tMemberMachine);
        int bindStatus = machineMapper.updateMachineBindStatus(machineId);
        if(insert > 0 && bindStatus > 0){
            return OperateResponse.obtainSuccessResponse(true);
        }else{
            return OperateResponse.failResponse("绑定失败！");
        }
    }

    @Override
    public OperateResponse deliverGood(String machineId, String lingSort, String itemId, Integer num) {
        List<TChannelProduct> hasDeliverGood = channelProductMapper.getHasDeliverGood(lingSort, itemId);
        if(hasDeliverGood == null || hasDeliverGood.size() < 1){
            TChannelProduct channelProduct = new TChannelProduct();
            channelProduct.setCreateDatetime(new Date());
            channelProduct.setProductNum(num);
            channelProduct.setProductSurplusNum(0);
            channelProduct.settChannelId(lingSort);
            channelProduct.settMachineId(machineId);
            channelProduct.settProductId(itemId);
            channelProduct.settChannelProductId(UUIDUtil.generate());
            int insert = channelProductMapper.insert(channelProduct);
            if(insert > 0){
                return OperateResponse.obtainSuccessResponse(true);
            }else{
                return OperateResponse.failResponse("上货失败!");
            }
        }else{
            channelProductMapper.decreaseProduct(hasDeliverGood.get(0).getProductNum()+num, lingSort);
            return OperateResponse.obtainSuccessResponse(true);
        }

    }

    /**
     * 机器提交故障信息
     * 成功返回数据格式：
     * {"ds":[{"result":"success"}]}
     * @param machineId    机器IMEI
     * @param errorCode     错误码
     * @return
     */
    @Override
    public JSONObject malfunction(String machineId, String errorCode) {
        JSONObject resultObject = new JSONObject();
        JSONObject returnObject = new JSONObject();
        List<JSONObject> list = new LinkedList<>();
        //更新机器状态
        int malfunction = machineMapper.malfunction(machineId, errorCode);
        if(malfunction > 0){
            resultObject.put("result", "success");
        }else{
            resultObject.put("result", "fail");
        }
        list.add(resultObject);
        returnObject.accumulate("ds", list);
        return returnObject;
    }


    /**
     * 机器请求获取订单
     * 成功返回数据格式：
     * {"ds":[{"line_sort":2,"trade_no":"4543333","count":1}]}
     * @param machineId
     * @return
     */
    @Override
    public JSONObject getOrder(String machineId) {
//        JSONObject resultObject = new JSONObject();
        JSONObject returnObject = new JSONObject();
//        List<JSONObject> list = new LinkedList<>();
        LinkedList<OrderItem> order = OrderHashMap.getSingleton().getOrderItem(machineId);

//        resultObject.accumulate("line_sort", 1);
//        resultObject.accumulate("trade_no", 1);
//        resultObject.accumulate("count", 1);
//        list.add(resultObject);
        if(order == null || order.size() < 1){
            LinkedList<OrderItem> emptyList = new LinkedList<>();
            emptyList.add(new OrderItem());
            order = emptyList;
            returnObject.accumulate("ds", order);
        }else{
            returnObject.accumulate("ds", order);
        }
        return returnObject;
    }


    /**
     * 机器更新订单
     * 成功返回数据格式：
     * {"ds":[{"result":"success"}]}
     * @param machineId     机器IMEI
     * @param tradeNo       订单号
     * @param state         (接受到订单指令:2,已出货指令:3)
     * @param lineSort      货到号
     * @param count         出货数量
     * @return
     */
    @Override
    public JSONObject updateOrder(String machineId, String tradeNo, Integer state, Integer lineSort, Integer count) {
        JSONObject resultObject = new JSONObject();
        JSONObject returnObject = new JSONObject();
        List<JSONObject> list = new LinkedList<>();
        //更新订单状态




        resultObject.put("result", "success");
        list.add(resultObject);
        returnObject.accumulate("ds", list);
        return returnObject;
    }

    @Override
    public OperateResponse recover(List<String> machineIds) {
        machineMapper.recover(machineIds);
        return OperateResponse.obtainSuccessResponse(true);
    }
}
